const config = require('./config')
const { getServerIP } = require('./utils/index')

function initSocket(app) {
  const server = require('http').Server(app.callback())
  const io = require('socket.io')(server)
  const serverIP = getServerIP()

  server.listen(config.socket_prot, () => {
    console.log(`web-socket run at : ws://${serverIP}:${config.socket_prot}`)
  })

  io.on('connection', socket => {
    socket.emit('server-message', '链接成功')

    socket.on('client-message', data => {
      // 返回给发送者(只有自己)
      socket.emit('chat-update', data)
      // 发送个其他人(不包括自己)
      socket.broadcast.emit('chat-update', data)
    })
  })
}

module.exports = initSocket
